<?php
namespace Hangpu888\Hpadmin;

use Hangpu888\Hpadmin\model\AuthRule;
use Hangpu888\Hpadmin\utils\manager\AuthManager;
use Hangpu888\Hpadmin\utils\manager\DataManager;
use Webman\Route;

class Routes
{
    // 初始化路由
    public function initify()
    {
        $data = $this->getRoutes();
        foreach ($data as $value) {
            Route::add($value['methods'], $value['route'], $value['namespace'])
            ->middleware([
                \Hangpu888\Hpadmin\middleware\CorsMiddleware::class,
                \Hangpu888\Hpadmin\middleware\Auths::class
            ]);
        }
    }

    /**
     * 获取路由规则
     *
     * @return array
     */
    private function getRoutes() : array
    {
        $list = AuthRule::whereNotIn('type',['group','remote'])->order('id desc')->select()->toArray();
        $data = [];
        foreach ($list as $value) {
            $data[$value['path']]['methods']        = explode(',',$value['method']);
            $data[$value['path']]['route']          = "/{$value['client']}/{$value['path']}";
            list($controller, $action)              = explode('/', $value['path']);
            if ($value['client'] == 'hpadmin') {
                $data[$value['path']]['namespace']      = "\\Hangpu888\\Hpadmin\\controller\\{$controller}@{$action}";
            }else{
                $data[$value['path']]['namespace']      = "app\\{$value['client']}\\controller\\{$controller}@{$action}";
            }
        }
        return $data;
    }

    /**
     * 读取数据库权限规则
     *
     * @return void
     */
    public function getAuthRules()
    {
        $menusMap['show'] = 1;
        $menus = AuthRule::where($menusMap)
        ->order('sort asc,id asc')
        ->select()
        ->toArray();
        $menuList = [];

        // 实例权限类
        $auth = new AuthManager((int)request()->user->id,(int)request()->user->role->is_system);

        // 拼接菜单数据
        $i = 0;
        foreach ($menus as $value) {
            // 检测是否有权限
            if ($auth->check($value['path'])) {
                $menuList[$i] = $value;
                $paramsValue = $value['params'] ? '_'.str_replace('=','_',$value['params']) : '';
                $menuList[$i]['spath'] = "{$value['path']}{$paramsValue}";
                $i++;
            }
        }

        $routes = AuthRule::whereNotIn('type', ['group','router'])
        ->select()
        ->toArray();
        $i = 0;
        $routeList = [];
        foreach ($routes as $value) {
            // 检测是否有权限
            if ($auth->check($value['path'])) {
                $routeList[$i] = $value;
                $i++;
            }
        }
        // 拼接路由
        $data['routes'] = $this->parseRoutes($routeList);

        // 多级菜单
        $list = DataManager::channelLevel($menuList,'','','spath','pid');
        $data['menus'] = $this->parseMenus($list);
        return $data;
    }

    /**
     * 解析路由规则
     *
     * @return void
     */
    private function parseRoutes($data)
    {
        $components = [
            'welcome'                           => 'index/welcome',
            'form'                              => 'form/index',
            'list'                              => 'table/index',
            'remote'                            => 'remote/index',
            'router'                            => 'form',
        ];
        $routes = [];
        foreach ($data as $key => $value) {
            $component = $components[$value['type']];
            $routes[$key] = [
                'name'                          => str_replace('/','_',$value['path']),
                'path'                          => "/{$value['client']}/{$value['path']}",
                'meta'                          => [
                    'component'                 => $component,
                    'title'                     => $value['title']
                ],
            ];
        }
        return $routes;
    }

    /**
     * 解析菜单规则
     *
     * @return void
     */
    private function parseMenus($data)
    {
        $menus = [];
        $i = 0;
        foreach ($data as $value) {
            $methods                            = explode(',',$value['method']);
            $method                             = current($methods);
            $menus[$i]['name']                  = str_replace('/','_',$value['path']);
            $menus[$i]['path']                  = "/{$value['client']}/{$value['path']}";
            $menus[$i]['params']                = [
                'title'                         => $value['title'],
                'method'                        => $method,
                'http'                          => "/{$value['client']}/{$value['path']}",
                'show'                          => $value['show'],
                'icon'                          => $value['icon'],
                'form_data'                     => $value['params']
            ];
            $menus[$i]['children']              = [];
            if ($value['_data']) {
                $menus[$i]['children']          = $this->parseMenus($value['_data']);
            }
            $i++;
        }
        return $menus;
    }
}